use std::time::Duration;

use async_trait::async_trait;
use base_data::channel::EndReason;
use tools::{utils::gen_id::get_now_duration, ResultNull};
use tracing::{debug, info};

use crate::{
	business::{
		bus_trait::Business,
		inbound400::context::{BusinessState, InboundRunContext},
	},
	config::business_config,
	link_to_sip::play_sound_file_to_caller,
};

#[derive(Debug, Clone)]
pub struct AllBusy;
//  {
// 	play_time: u64,
// 	now_check_play_stop: bool,
// }

impl Default for AllBusy {
	fn default() -> Self {
		Self
	}
}

#[async_trait]
impl Business for AllBusy {
	type C = InboundRunContext;

	async fn check(&self, context: &mut InboundRunContext) -> ResultNull {
		if get_now_duration() > context.check_time + Duration::from_secs(20) {
			context.business_state = BusinessState::End(EndReason::TalkNocallerd);
		}

		Ok(())
	}

	async fn play_back_stop(&self, context: &mut InboundRunContext,_channel_id:u32) -> ResultNull {
		//有可能收到的是上一次播放得到的结束事件.所以需要进行判断
		if get_now_duration() > context.check_time + Duration::from_secs(1) {
			info!("全忙，播放结束,退出。");
			context.business_state = BusinessState::End(EndReason::AllBusy);
		} else {
			debug!("全忙，收到播放结束消息，但不需要的，跳过");
			context.business_state = BusinessState::End(EndReason::AllBusy);
		}

		Ok(())
	}
	
	async fn hangup(
		&self,
		context: &mut InboundRunContext,
		_channel_id: u32,
		_reason: EndReason,
	) -> ResultNull {	
			context.business_state = BusinessState::End(EndReason::AllBusy);

		Ok(())
	}

	async fn start_call(&self, context: &mut InboundRunContext) -> ResultNull {
		context.check_time = get_now_duration();
		play_sound_file_to_caller(
			context.caller_channel(),
			business_config().phone_busy_bell_path,
		)?;

		Ok(())
	}
}
